import 'package:awak/common/routers/router_names.dart';
import 'package:awak/common/utils/util_text.dart';
import 'package:awak/common/utils/util_dialog.dart';
import 'package:awak/common/models/room.dart';
import 'package:awak/common/models/comment.dart';
import 'package:awak/common/models/user.dart';
import 'package:awak/common/models/topic.dart';
import 'package:awak/common/models/content.dart';
import 'package:awak/common/repository/comment_repository.dart';
import 'package:awak/common/repository/user_repository.dart';
import 'package:awak/common/repository/content_repository.dart';
import 'package:awak/common/repository/review_repository.dart';
import 'package:awak/common/repository/favorite_repository.dart';
import 'package:awak/common/values/svg.dart';

import 'package:awak/page/community/room_data_holder.dart';
import 'package:awak/page/community/topic_data_holder.dart';
import 'package:awak/page/community/content_data_holder.dart';
import 'package:awak/page/community/content_release_page.dart';
import 'package:awak/page/profile/user_data_holder.dart';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../common/values/images.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/auth/auth_bloc.dart';
import '../../bloc/auth/auth_event.dart';
import '../../bloc/auth/auth_state.dart';

class CommunityPage extends StatefulWidget {
  const CommunityPage({super.key});

  @override
  State<CommunityPage> createState() => _CommunityPageState();
}

class _CommunityPageState extends State<CommunityPage> with WidgetsBindingObserver {
  List<String> defaultPeople = [
    '32 People',
    '41 People',
    '56 People',
    '46 People',
  ];
  List<String> defaultButton = ['Chat', 'Discuss', 'Reading', 'Inbetweening'];

  final CommentRepository _commentRepository = CommentRepository();
  final UserRepository _userRepository = UserRepository();
  final ContentRepository _contentRepository = ContentRepository();
  final ReviewRepository _reviewRepository = ReviewRepository();
  final FavoriteRepository _favoriteRepository = FavoriteRepository();

  // 缓存房间的评论数据
  final Map<int, List<Comment>> _roomCommentsCache = {};
  final Map<int, List<User>> _roomCommentersCache = {};

  // 缓存主题的内容数量
  final Map<int, int> _topicContentCountCache = {};

  // 缓存所有主题的内容
  List<Content> _allTopicContents = [];
  Map<int, User> _contentUsersCache = {};
  Map<int, int> _contentReviewCounts = {};
  Map<int, bool> _contentFavoriteStatus = {};
  bool _isLoadingContents = false;

  // 缓存房间数据，避免状态丢失
  List<Room> _cachedRooms = [];

  // 排序状态：0 = Latest, 1 = Hot
  int _sortType = 0;

  // 标签切换状态：0 = Study, 1 = Community
  int _selectedTabIndex = 0; // 默认选中 Community

  // 当前选中的主题
  Topic? _currentTopic;

  // 获取房间的评论数据
  Future<void> _loadRoomComments(Room room) async {
    if (room.id == null) return;

    try {
      final comments = await _commentRepository.getCommentsByRoomId(room.id!);
      _roomCommentsCache[room.id!] = comments;

      // 获取评论者信息
      Set<int> userIds = comments.map((c) => c.userId).toSet();
      List<User> commenters = [];

      for (int userId in userIds) {
        final user = await _userRepository.getUserById(userId);
        if (user != null) {
          commenters.add(user);
        }
      }

      _roomCommentersCache[room.id!] = commenters;

      if (mounted) {
        setState(() {});
      }
    } catch (e) {
      print('Error loading comments for room ${room.id}: $e');
    }
  }

  // 获取主题的内容数量
  Future<void> _loadTopicContentCount(Topic topic) async {
    if (topic.id == null) return;

    try {
      final count = await _contentRepository.getContentCountByTopicId(topic.id!);
      _topicContentCountCache[topic.id!] = count;

      if (mounted) {
        setState(() {});
      }
    } catch (e) {
      print('Error loading content count for topic ${topic.id}: $e');
    }
  }

  // 获取主题的内容数量
  int _getTopicContentCount(Topic topic) {
    if (topic.id == null) return 0;
    return _topicContentCountCache[topic.id] ?? int.tryParse(topic.content) ?? 0;
  }

  // 加载所有主题的内容
  Future<void> _loadAllTopicContents() async {
    if (_isLoadingContents) return;

    setState(() {
      _isLoadingContents = true;
    });

    try {
      // 根据排序类型获取内容
      final allContents = _sortType == 0
          ? await _contentRepository.getAllContentsByLatest()
          : await _contentRepository.getAllContentsByHot();

      // 获取所有相关用户信息
      Set<int> userIds = allContents.map((c) => c.userId).toSet();
      Map<int, User> users = {};

      for (int userId in userIds) {
        final user = await _userRepository.getUserById(userId);
        if (user != null) {
          users[userId] = user;
        }
      }

      // 获取所有内容的评论数量
      Map<int, int> reviewCounts = {};
      for (Content content in allContents) {
        if (content.id != null) {
          final count = await _reviewRepository.getReviewCountByContentId(content.id!);
          reviewCounts[content.id!] = count;
        }
      }

      // 获取当前用户的收藏状态
      Map<int, bool> favoriteStatus = {};
      final currentUser = _userRepository.currentUser;
      if (currentUser?.id != null) {
        for (Content content in allContents) {
          if (content.id != null) {
            final isFavorited = await _favoriteRepository.isFavorited(currentUser!.id!, content.id!);
            favoriteStatus[content.id!] = isFavorited;
          }
        }
      }

      if (mounted) {
        setState(() {
          _allTopicContents = allContents;
          _contentUsersCache = users;
          _contentReviewCounts = reviewCounts;
          _contentFavoriteStatus = favoriteStatus;
          _isLoadingContents = false;
        });
      }
    } catch (e) {
      print('Error loading all topic contents: $e');
      if (mounted) {
        setState(() {
          _isLoadingContents = false;
        });
      }
    }
  }

  // 切换排序类型
  void _changeSortType(int sortType) {
    if (_sortType != sortType) {
      setState(() {
        _sortType = sortType;
      });
      _loadAllTopicContents(); // 重新加载内容
    }
  }

  // 切换收藏状态
  Future<void> _toggleFavorite(Content content) async {
    final currentUser = _userRepository.currentUser;
    if (currentUser?.id == null || content.id == null) return;

    try {
      final newStatus = await _favoriteRepository.toggleFavorite(currentUser!.id!, content.id!);
      setState(() {
        _contentFavoriteStatus[content.id!] = newStatus;
      });
    } catch (e) {
      // 处理错误，可以显示提示信息
      print('Error toggling favorite: $e');
    }
  }

  // 获取房间的评论数量
  int _getRoomCommentCount(Room room) {
    if (room.id == null) return 0;
    return _roomCommentsCache[room.id]?.length ?? 0;
  }

  // 获取房间的评论者头像列表
  List<User> _getRoomCommenters(Room room) {
    if (room.id == null) return [];
    return _roomCommentersCache[room.id] ?? [];
  }

  // 构建热度图标
  Widget _buildHotIcons(Room room, {double? iconSize}) {
    final commentCount = _getRoomCommentCount(room);

    // 根据评论数量决定显示几个火焰图标
    int fireCount = 0;
    if (commentCount >= 8) {
      fireCount = 3;
    } else if (commentCount >= 5) {
      fireCount = 2;
    } else if (commentCount >= 1) {
      fireCount = 1;
    }

    if (fireCount == 0) {
      return SizedBox.shrink();
    }

    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(
        fireCount,
        (index) => Icon(
          Icons.local_fire_department,
          color: Colors.orange,
          size: iconSize ?? 16.w,
        ),
      ),
    );
  }

  // 构建评论者头像组件
  Widget _buildCommentersAvatars(Room room) {
    final commenters = _getRoomCommenters(room);
    _getRoomCommentCount(room);

    if (commenters.isEmpty) {
      return Container(
        width: 20.w,
        height: 20.h,
        decoration: BoxDecoration(
          color: Colors.grey.withValues(alpha: 0.3),
          shape: BoxShape.circle,
          border: Border.all(color: Colors.black, width: 1.w),
        ),
        child: Icon(Icons.person, size: 12.w, color: Colors.grey),
      );
    }

    List<Widget> avatars = [];

    if (commenters.length <= 3) {
      // 如果评论者不超过3个，显示所有头像
      for (int i = 0; i < commenters.length; i++) {
        avatars.add(
          Positioned(
            left: i * 12.w,
            child: Container(
              width: 20.w,
              height: 20.h,
              decoration: BoxDecoration(
                color: Colors.white,
                shape: BoxShape.circle,
                border: Border.all(color: Colors.black, width: 1.w),
                image: DecorationImage(
                  image: AssetImage(commenters[i].avatar ?? AwakImages.avatar),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
        );
      }
    } else {
      // 如果超过3个评论者，只显示前2个头像，然后显示 +数字
      for (int i = 0; i < 2; i++) {
        avatars.add(
          Positioned(
            left: i * 12.w,
            child: Container(
              width: 20.w,
              height: 20.h,
              decoration: BoxDecoration(
                color: Colors.white,
                shape: BoxShape.circle,
                border: Border.all(color: Colors.black, width: 1.w),
                image: DecorationImage(
                  image: AssetImage(commenters[i].avatar ?? AwakImages.avatar),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
        );
      }

      // 添加 +数字 显示
      avatars.add(
        Positioned(
          left: 2 * 12.w,
          child: Container(
            width: 20.w,
            height: 20.h,
            decoration: BoxDecoration(
              color: Colors.black,
              shape: BoxShape.circle,
              border: Border.all(color: Colors.black, width: 1.w),
            ),
            child: Center(
              child: Text(
                '+${commenters.length - 2}',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 8.sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ),
      );
    }

    // 计算容器宽度
    int totalItems = commenters.length > 3 ? 3 : commenters.length;

    return SizedBox(
      width: totalItems * 12.w + 8.w,
      height: 20.h,
      child: Stack(children: avatars),
    );
  }

  // 获取 Room Recommendations 房间列表 (ID: 5-8)
  List<Room> _getRecommendationRooms(List<Room> allRooms) {
    return allRooms
        .where((room) => room.id != null && room.id! >= 5 && room.id! <= 8)
        .toList();
  }

  // 获取所有的房间列表
  List<Room> _getAllRooms(List<Room> allRooms) {
    return allRooms;
  }

  // 构建 Community 页面内容
  Widget _buildCommunityContent() {
    return Column(
      children: [
        SizedBox(height: 10.h),
        GestureDetector(
          onTap: () => _handleTopicCardTap(),
          child: Container(
            margin: EdgeInsets.symmetric(horizontal: 16.w),
            decoration: BoxDecoration(
              color: const Color(0xFFD3F427),
              borderRadius: BorderRadius.circular(16.r),
              border: Border.all(color: Colors.black, width: 2.w),
            ),
            child: Column(
            children: [
              Container(
                padding: EdgeInsets.all(12.w),
                decoration: BoxDecoration(
                  color: const Color(0xFFFFF45C),
                  borderRadius: BorderRadius.circular(16.r),
                  border: Border(
                    bottom: BorderSide(color: Colors.black, width: 2.w),
                  ),
                ),
                child: Row(
                  children: [
                    Container(
                      width: 84.w,
                      height: 96.h,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16.r),
                        border: Border.all(color: Colors.black, width: 2.w),
                        image: DecorationImage(
                          image: AssetImage(
                            _currentTopic?.coverImage ?? AwakImages.topic1,
                          ),
                          fit: BoxFit.contain,
                        ),
                      ),
                    ),
                    SizedBox(width: 16.w),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            _currentTopic?.title ??
                                'Philosophical Thinking Topic Arrivals!',
                            style: AwakText.body16Style.copyWith(
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          SizedBox(height: 8.h),

                          Row(
                            children: [
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      'Content: ${_currentTopic != null ? _getTopicContentCount(_currentTopic!) : '0'}',
                                      style: AwakText.body14Style.copyWith(
                                        color: Colors.grey[600],
                                        fontSize: 12.sp,
                                      ),
                                    ),
                                    SizedBox(height: 4.h),
                                    Text(
                                      'Number People: ${_getCurrentTopicPeopleCount()}',
                                      style: AwakText.body14Style.copyWith(
                                        color: Colors.grey[600],
                                        fontSize: 12.sp,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              GestureDetector(
                                onTap: () => _handleJoinButtonTap(),
                                child: Container(
                                  padding: EdgeInsets.symmetric(
                                    horizontal: 24.w,
                                    vertical: 8.h,
                                  ),
                                  decoration: BoxDecoration(
                                    color: _isCurrentTopicJoined()
                                        ? Colors.grey
                                        : const Color(0xFF8B5CF6),
                                    borderRadius: BorderRadius.circular(20.r),
                                    border: Border.all(
                                      color: Colors.black,
                                      width: 2.w,
                                    ),
                                  ),
                                  child: Text(
                                    _isCurrentTopicJoined()
                                        ? 'Joined'
                                        : 'Join',
                                    style: AwakText.body14Style.copyWith(
                                      color: Colors.white,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: EdgeInsetsGeometry.all(12.w),
                child: Row(
                  children: [
                    Text('Topic Recommendation', style: AwakText.body16Style),
                  ],
                ),
              ),
              Wrap(
                spacing: 8.w,
                runSpacing: 10.h,
                children: TopicDataHolder.getRecommendationTopics()
                    .map((topic) => _buildTopicTag(topic))
                    .toList(),
              ),
              SizedBox(height: 12.h),
            ],
          ),
        ),
        ),
        SizedBox(height: 10.h),
        // Community Updates
        Padding(
          padding: EdgeInsetsGeometry.only(left: 16.w, right: 16.w, top: 16.h),
          child: Row(
            children: [
              Text(
                'Community Updates',
                style: AwakText.body16Style.copyWith(
                  fontWeight: FontWeight.bold,
                ),
              ),
              Spacer(),
              GestureDetector(
                onTap: () => _changeSortType(1), // Hot排序
                child: Text(
                  'Hot',
                  style: AwakText.body14Style.copyWith(
                    fontWeight: FontWeight.w500,
                    color: _sortType == 1 ? Colors.black : Colors.grey,
                  ),
                ),
              ),
              SizedBox(width: 10.w),
              GestureDetector(
                onTap: () => _changeSortType(0), // Latest排序
                child: Text(
                  'Latest',
                  style: AwakText.body14Style.copyWith(
                    fontWeight: FontWeight.w500,
                    color: _sortType == 0 ? Colors.black : Colors.grey,
                  ),
                ),
              ),
            ],
          ),
        ),
        Row(
          children: [
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 4.h),
              child: Text(
                'Record user updates shared on the square',
                style: AwakText.body14Style.copyWith(
                  fontWeight: FontWeight.w400,
                  fontSize: 10.sp,
                  color: Colors.black.withValues(alpha: 0.7),
                ),
              ),
            ),
          ],
        ),
        SizedBox(height: 15.h),
        // 用户发布的内容
        _buildAllTopicContents(),
      ],
    );
  }

  // 构建所有主题的内容列表
  Widget _buildAllTopicContents() {
    if (_isLoadingContents) {
      return Center(
        child: Padding(
          padding: EdgeInsets.all(40.h),
          child: CircularProgressIndicator(),
        ),
      );
    }

    if (_allTopicContents.isEmpty) {
      return Center(
        child: Padding(
          padding: EdgeInsets.all(40.h),
          child: Text(
            'No content available yet',
            style: AwakText.body14Style.copyWith(
              color: Colors.grey,
            ),
          ),
        ),
      );
    }

    return Column(
      children: [
        ..._allTopicContents.map((content) => _buildTopicContentCard(content)),
        SizedBox(height: 120.h),
      ],
    );
  }

  // 构建单个主题内容卡片
  Widget _buildTopicContentCard(Content content) {
    final user = _contentUsersCache[content.userId];
    final userName = user?.nickname ?? user?.username ?? 'Unknown User';
    final userAvatar = user?.avatar ?? AwakImages.avatar;
    final userSignature = user?.signature ?? 'No signature';

    // 获取内容所属的主题信息
    final topic = TopicDataHolder.getTopicById(content.topicId);
    final topicLabel = topic?.label ?? 'Unknown Topic';

    // 获取评论数量
    final reviewCount = _contentReviewCounts[content.id] ?? 0;

    return GestureDetector(
      onTap: () {
        // 设置当前内容并跳转到内容详情页
        ContentDataHolder.setCurrentContent(content);
        Beamer.of(context).beamToNamed(RouterNames.detailContent);
      },
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
        decoration: BoxDecoration(color: Colors.transparent),
        child: Column(
          children: [
            Row(
              children: [
                GestureDetector(
                  onTap: () {
                    if (user != null) {
                      UserDataHolder.setCurrentUser(user);
                      Beamer.of(context).beamToNamed(RouterNames.otherProfile);
                    }
                  },
                  child: Container(
                    width: 60.w,
                    height: 60.h,
                    decoration: BoxDecoration(
                      color: Colors.transparent,
                      border: Border.all(color: Colors.black, width: 1.w),
                      shape: BoxShape.circle,
                      image: DecorationImage(
                        image: AssetImage(userAvatar),
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                ),
                SizedBox(width: 10.w),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(userName, style: AwakText.body16Style),
                      Text(
                        userSignature,
                        style: AwakText.body14Style.copyWith(
                          color: Colors.grey,
                          fontSize: 12.sp,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      // 显示主题标签
                      GestureDetector(
                        onTap: () {
                          if (topic != null) {
                            // 设置当前主题并跳转到主题详情页
                            TopicDataHolder.setCurrentTopic(topic);
                            Beamer.of(context).beamToNamed(RouterNames.detailTopic);
                          }
                        },
                        child: Container(
                          margin: EdgeInsets.only(top: 4.h),
                          padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 2.h),
                          decoration: BoxDecoration(
                            color: const Color(0xFFD3F427),
                            borderRadius: BorderRadius.circular(12.r),
                            border: Border.all(color: Colors.black, width: 1.w),
                          ),
                          child: Text(
                            topicLabel,
                            style: AwakText.body14Style.copyWith(
                              fontSize: 10.sp,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 6.h),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  child: Row(
                    children: [
                      Icon(AwakSvg.report, size: 20.w),
                      SizedBox(width: 6.w),
                      Text(
                        'Issue',
                        style: AwakText.body14Style.copyWith(
                          color: Colors.black,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            SizedBox(height: 10.h),
            Image.asset(
              content.picture,
              height: 223.h,
              fit: BoxFit.cover,
            ),
            SizedBox(height: 10.h),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              child: Text(
                content.description,
                style: AwakText.body16Style.copyWith(
                  fontWeight: FontWeight.w500,
                  height: 1.5,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            SizedBox(height: 10.h),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Row(
                  children: [
                    Icon(AwakSvg.review, size: 28.sp),
                    SizedBox(width: 4.w),
                    Text(
                      '$reviewCount',
                      style: AwakText.body14Style.copyWith(
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ),
                SizedBox(width: 30.w),
                GestureDetector(
                  onTap: () => _toggleFavorite(content),
                  child: Icon(
                    _contentFavoriteStatus[content.id] == true
                        ? Icons.favorite
                        : AwakSvg.like,
                    size: 28.sp,
                    color: _contentFavoriteStatus[content.id] == true
                        ? Colors.red
                        : Colors.black,
                  ),
                ),
                SizedBox(width: 20.w),
              ],
            ),
            SizedBox(height: 20.h),
          ],
        ),
      ),
    );
  }



  // 构建主题标签
  Widget _buildTopicTag(Topic topic) {
    return GestureDetector(
      onTap: () {
        setState(() {
          // 获取最新的主题数据，包括可能更新的人数
          final updatedTopic = TopicDataHolder.getTopicById(topic.id!) ?? topic;
          _currentTopic = updatedTopic;
          // 使用新的方法确保ID和对象同步
          TopicDataHolder.setCurrentTopic(updatedTopic);
        });
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 8.h),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(20.r),
          border: Border.all(color: Colors.black, width: 1.w),
        ),
        child: Text(
          topic.label,
          style: AwakText.body14Style.copyWith(
            color: Colors.black.withValues(alpha: 0.6),
            fontSize: 12.sp,
          ),
        ),
      ),
    );
  }

  // 处理 Join 按钮点击事件
  void _handleJoinButtonTap() async {
    if (_currentTopic == null) return;

    if (TopicDataHolder.isTopicJoined(_currentTopic!.id)) {
      // 已经加入，不做任何操作
      return;
    }

    showAwakDialog(
      context: context,
      title: 'Join Topic',
      description: 'Are you sure you want to join this topic?',
      onConfirm: () async {
        // 加入主题
        TopicDataHolder.joinTopic(_currentTopic!.id);
        // 更新人数
        final newCount = (_currentTopic!.numberPeople) + 1;
        await TopicDataHolder.updateTopicPeopleCount(_currentTopic!.id, newCount);

        if (mounted) {
          setState(() {
            _currentTopic = _currentTopic!.copyWith(numberPeople: newCount);
            TopicDataHolder.currentTopic = _currentTopic;
          });
        }
      },
    );
  }

  // 处理主题卡片点击事件
  void _handleTopicCardTap() {
    if (_currentTopic == null) return;

    if (TopicDataHolder.isTopicJoined(_currentTopic!.id)) {
      // 已加入，可以查看详情
      TopicDataHolder.currentTopic = _currentTopic;
      Beamer.of(context).beamToNamed(RouterNames.detailTopic);
    } else {
      // 未加入，显示提示
      showAwakDialog(
        context: context,
        title: 'Access Denied',
        description: 'You must first join the topic before you can view the details.',
        onConfirm: () {
          // 什么都不做，只是关闭对话框
        },
      );
    }
  }

  // 处理 Issue 按钮点击事件
  void _handleIssueButtonTap() async {
    // 跳转到内容发布页面，并等待返回结果
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const ContentReleasePage(),
      ),
    );

    // 如果用户发布了内容，刷新Community Updates
    if (result == true) {
      _refreshCommunityUpdates();
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 确保主题状态一致性
      TopicDataHolder.ensureCurrentTopicConsistency();
      // 获取所有房间
      context.read<AwakBloc>().add(FetchRoomsEvent());
      // 获取所有主题
      context.read<AwakBloc>().add(FetchTopicsEvent());
      // 加载所有主题的内容
      _loadAllTopicContents();
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      // 当应用恢复时，刷新当前主题状态和内容
      _refreshCurrentTopicState();
      _refreshCommunityUpdates();
    }
  }

  // 刷新Community Updates内容
  void _refreshCommunityUpdates() {
    _loadAllTopicContents();
  }







  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 当页面重新获得焦点时，刷新当前主题状态
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _refreshCurrentTopicState();
    });
  }

  // 刷新当前主题状态
  void _refreshCurrentTopicState() {
    // 优先使用TopicDataHolder中记录的当前主题ID
    if (TopicDataHolder.currentTopicId != null) {
      final targetTopic = TopicDataHolder.getTopicById(TopicDataHolder.currentTopicId!);
      if (targetTopic != null && mounted) {
        // 检查是否需要更新当前显示的主题
        bool needsUpdate = false;

        if (_currentTopic == null || _currentTopic!.id != targetTopic.id) {
          needsUpdate = true;
        } else {
          // 检查数据是否有变化
          if (_currentTopic!.numberPeople != targetTopic.numberPeople) {
            needsUpdate = true;
          }

          if (TopicDataHolder.isTopicJoined(_currentTopic!.id) !=
              TopicDataHolder.isTopicJoined(targetTopic.id)) {
            needsUpdate = true;
          }
        }

        if (needsUpdate) {
          setState(() {
            _currentTopic = targetTopic;
            TopicDataHolder.currentTopic = targetTopic;
          });
        }
      }
    } else if (_currentTopic != null) {
      // 如果没有设置currentTopicId，但有currentTopic，则更新数据
      final updatedTopic = TopicDataHolder.getTopicById(_currentTopic!.id!);
      if (updatedTopic != null && mounted) {
        bool hasChanges = false;

        if (_currentTopic!.numberPeople != updatedTopic.numberPeople) {
          hasChanges = true;
        }

        if (TopicDataHolder.isTopicJoined(_currentTopic!.id) !=
            TopicDataHolder.isTopicJoined(updatedTopic.id)) {
          hasChanges = true;
        }

        if (hasChanges) {
          setState(() {
            _currentTopic = updatedTopic;
            TopicDataHolder.currentTopic = updatedTopic;
          });
        }
      }
    }
  }

  // 获取当前主题的最新人数
  int _getCurrentTopicPeopleCount() {
    if (_currentTopic?.id != null) {
      // 优先从缓存获取最新人数
      return TopicDataHolder.getTopicPeopleCount(_currentTopic!.id!);
    }
    return _currentTopic?.numberPeople ?? 98;
  }

  // 检查当前主题是否已加入
  bool _isCurrentTopicJoined() {
    return TopicDataHolder.isTopicJoined(_currentTopic?.id);
  }

  @override
  void didUpdateWidget(CommunityPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 当widget更新时也刷新状态
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _refreshCurrentTopicState();
    });
  }



  // 构建推荐房间卡片的方法
  Widget _buildRoomCard(Room room, {VoidCallback? onTap}) {
    final commentCount = _getRoomCommentCount(room);

    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.all(8.w),
        child: Row(
          children: [
            // 图片
            ClipRRect(
              borderRadius: BorderRadius.circular(8.r),
              child: Image.asset(
                room.roomAvatar,
                width: 60.w,
                height: 60.h,
                fit: BoxFit.cover,
              ),
            ),
            SizedBox(width: 12.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    room.roomName.replaceAll(' ', '\n'),
                    style: AwakText.body14Style.copyWith(
                      fontWeight: FontWeight.w600,
                      fontSize: 12.sp,
                      color: Colors.black,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 4.h),
                  // 显示评论人数
                  Text(
                    '$commentCount People',
                    style: AwakText.body14Style.copyWith(
                      fontWeight: FontWeight.w400,
                      fontSize: 10.sp,
                      color: Colors.black.withValues(alpha: 0.7),
                    ),
                  ),
                  SizedBox(height: 4.h),
                  _buildHotIcons(room, iconSize: 16.w),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLearningRoomCard(
    dynamic room,
    String buttonText,
    String peopleText,
  ) {
    return GestureDetector(
      onTap: () {
        // 设置全局变量
        RoomDataHolder.currentRoom = room;
        Beamer.of(context).beamToNamed(RouterNames.detailRoom, data: room);
      },
      child: Column(
        children: [
          Stack(
            children: [
              Image.asset(
                room.roomAvatar,
                width: 162.w,
                height: 162.h,
                fit: BoxFit.cover,
              ),
              Positioned(
                top: 10.h,
                left: 10.w,
                child: Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 10.w,
                    vertical: 5.h,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(100.r),
                    border: Border.all(color: Colors.black, width: 1.w),
                  ),
                  child: Text(
                    buttonText,
                    style: AwakText.body14Style.copyWith(
                      fontWeight: FontWeight.w600,
                      fontSize: 12.sp,
                      color: Colors.black,
                    ),
                  ),
                ),
              ),
            ],
          ),
          SizedBox(height: 10.h),
          Container(
            width: 162.w,
            decoration: BoxDecoration(color: Colors.transparent),
            child: Text(
              room.roomName,
              style: AwakText.body14Style.copyWith(
                fontWeight: FontWeight.w400,
                fontSize: 12.sp,
                color: Colors.black,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          SizedBox(height: 10.h),
          Container(
            width: 162.w,
            decoration: BoxDecoration(color: Colors.transparent),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                _buildCommentersAvatars(room),
                SizedBox(width: 6.w),
                Text(
                  '${_getRoomCommentCount(room)} People',
                  style: AwakText.body14Style.copyWith(
                    fontWeight: FontWeight.w400,
                    fontSize: 12.sp,
                    color: Colors.black.withValues(alpha: 0.7),
                  ),
                ),
                Spacer(),
                _buildHotIcons(room, iconSize: 18.w),
              ],
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 每次构建时检查并刷新主题状态
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _refreshCurrentTopicState();
    });

    return Scaffold(
      body: BlocListener<AwakBloc, AwakState>(
        listener: (context, state) {
          // 缓存房间数据
          if (state is RoomsLoaded) {
            setState(() {
              _cachedRooms = state.rooms;
            });
          } else if (state is TopicsLoaded) {
            setState(() {
              TopicDataHolder.allTopics = state.topics;
              // 如果TopicsLoaded包含房间数据，也缓存它
              if (state.rooms != null) {
                _cachedRooms = state.rooms!;
              }

              // 为所有主题加载内容数量
              for (Topic topic in state.topics) {
                _loadTopicContentCount(topic);
              }

              // 优先保持用户之前选择的主题
              if (TopicDataHolder.currentTopicId != null) {
                // 如果用户之前选择了主题，尝试恢复该主题
                final previousTopic = TopicDataHolder.getTopicById(TopicDataHolder.currentTopicId!);
                if (previousTopic != null) {
                  _currentTopic = previousTopic;
                  TopicDataHolder.currentTopic = previousTopic;
                } else if (state.topics.isNotEmpty) {
                  // 如果之前选择的主题不存在了，才使用第一个主题
                  TopicDataHolder.currentTopic = state.topics.first;
                  TopicDataHolder.currentTopicId = state.topics.first.id;
                  _currentTopic = state.topics.first;
                }
              } else if (TopicDataHolder.currentTopic == null && state.topics.isNotEmpty) {
                // 如果完全没有设置过主题，设置第一个哲学主题为默认
                TopicDataHolder.currentTopic = state.topics.first;
                TopicDataHolder.currentTopicId = state.topics.first.id;
                _currentTopic = state.topics.first;
              } else if (_currentTopic != null) {
                // 如果当前主题已存在，更新为最新数据
                final updatedTopic = TopicDataHolder.getTopicById(_currentTopic!.id!);
                if (updatedTopic != null) {
                  _currentTopic = updatedTopic;
                  TopicDataHolder.currentTopic = updatedTopic;
                }
              }
            });
          } else if (state is TopicLoaded) {
            setState(() {
              _currentTopic = state.topic;
              TopicDataHolder.currentTopic = state.topic;
              if (state.topic != null) {
                TopicDataHolder.currentTopicId = state.topic!.id;
              }
            });
          }
        },
        child: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage(AwakImages.editBg),
              fit: BoxFit.cover,
            ),
          ),
          child: Column(
            children: [
              SizedBox(height: 60.h),
              Row(
                children: [
                  SizedBox(width: 16.w),
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        _selectedTabIndex = 0; // 切换到 Study
                      });
                    },
                    child: Text(
                      'STUDY',
                      style: AwakText.titleStyle.copyWith(
                        color: _selectedTabIndex == 0
                            ? Colors.black
                            : Colors.grey,
                        fontWeight: _selectedTabIndex == 0
                            ? FontWeight.bold
                            : FontWeight.normal,
                      ),
                    ),
                  ),
                  SizedBox(width: 30.w),
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        _selectedTabIndex = 1; // 切换到 Community
                      });
                    },
                    child: Text(
                      'COMMUNITY',
                      style: AwakText.titleStyle.copyWith(
                        color: _selectedTabIndex == 1
                            ? Colors.black
                            : Colors.grey,
                        fontWeight: _selectedTabIndex == 1
                            ? FontWeight.bold
                            : FontWeight.normal,
                      ),
                    ),
                  ),
                  Spacer(),
                  GestureDetector(
                    onTap: () {
                      if (_selectedTabIndex == 1) {
                        // Community 页面 - Issue 按钮的点击事件
                        _handleIssueButtonTap();
                      } else {
                        // Study 页面 - Creation 按钮的点击事件
                        Beamer.of(
                          context,
                        ).beamToNamed(RouterNames.creationRoom);
                      }
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 12.w,
                        vertical: 8.h,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(100.r),
                        border: Border.all(color: Colors.black, width: 1.w),
                      ),
                      child: Text(
                        _selectedTabIndex == 1 ? 'Issue' : 'Creation',
                        style: AwakText.body14Style.copyWith(
                          color: Colors.black,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 16.w),
                ],
              ),
              SizedBox(height: 10.h),
              Expanded(
                child: SingleChildScrollView(
                  child: _selectedTabIndex == 0
                      ? Column(
                          // 显示 Study 内容
                          children: [
                            Builder(
                              builder: (context) {
                                // 使用缓存的房间数据
                                List<Room> allRooms = _cachedRooms;

                                // 为所有房间加载评论数据
                                for (Room room in allRooms) {
                                  if (room.id != null &&
                                      !_roomCommentsCache.containsKey(
                                        room.id,
                                      )) {
                                    _loadRoomComments(room);
                                  }
                                }

                                final recommendationRooms =
                                    _getRecommendationRooms(allRooms);

                                return Container(
                                  margin: EdgeInsets.symmetric(
                                    horizontal: 16.w,
                                    vertical: 10.h,
                                  ),
                                  padding: EdgeInsets.symmetric(
                                    horizontal: 12.w,
                                    vertical: 16.h,
                                  ),
                                  decoration: BoxDecoration(
                                    color: const Color(0xFFD3F427),
                                    borderRadius: BorderRadius.circular(16.r),
                                    border: Border.all(
                                      color: Colors.black,
                                      width: 2.w,
                                    ),
                                  ),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        'Room Recommendations',
                                        style: AwakText.body16Style.copyWith(
                                          color: Colors.black,
                                          fontWeight: FontWeight.w500,
                                        ),
                                      ),
                                      SizedBox(height: 15.h),
                                      if (recommendationRooms.length >= 4) ...[
                                        Column(
                                          children: [
                                            Row(
                                              children: [
                                                Expanded(
                                                  child: _buildRoomCard(
                                                    recommendationRooms[0],
                                                    onTap: () {
                                                      RoomDataHolder
                                                              .currentRoom =
                                                          recommendationRooms[0];
                                                      Beamer.of(
                                                        context,
                                                      ).beamToNamed(
                                                        RouterNames.detailRoom,
                                                        data:
                                                            recommendationRooms[0],
                                                      );
                                                    },
                                                  ),
                                                ),
                                                SizedBox(width: 12.w),
                                                Expanded(
                                                  child: _buildRoomCard(
                                                    recommendationRooms[1],
                                                    onTap: () {
                                                      RoomDataHolder
                                                              .currentRoom =
                                                          recommendationRooms[1];
                                                      Beamer.of(
                                                        context,
                                                      ).beamToNamed(
                                                        RouterNames.detailRoom,
                                                        data:
                                                            recommendationRooms[1],
                                                      );
                                                    },
                                                  ),
                                                ),
                                              ],
                                            ),
                                            SizedBox(height: 12.h),
                                            Row(
                                              children: [
                                                Expanded(
                                                  child: _buildRoomCard(
                                                    recommendationRooms[2],
                                                    onTap: () {
                                                      RoomDataHolder
                                                              .currentRoom =
                                                          recommendationRooms[2];
                                                      Beamer.of(
                                                        context,
                                                      ).beamToNamed(
                                                        RouterNames.detailRoom,
                                                        data:
                                                            recommendationRooms[2],
                                                      );
                                                    },
                                                  ),
                                                ),
                                                SizedBox(width: 12.w),
                                                Expanded(
                                                  child: _buildRoomCard(
                                                    recommendationRooms[3],
                                                    onTap: () {
                                                      RoomDataHolder
                                                              .currentRoom =
                                                          recommendationRooms[3];
                                                      Beamer.of(
                                                        context,
                                                      ).beamToNamed(
                                                        RouterNames.detailRoom,
                                                        data:
                                                            recommendationRooms[3],
                                                      );
                                                    },
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ],
                                        ),
                                      ] else ...[
                                        Text(
                                          'Loading recommendations...',
                                          style: AwakText.body14Style.copyWith(
                                            color: Colors.black.withValues(
                                              alpha: 0.7,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ],
                                  ),
                                );
                              },
                            ),
                            SizedBox(height: 10.h),
                            Row(
                              children: [
                                Padding(
                                  padding: EdgeInsets.symmetric(
                                    horizontal: 16.w,
                                  ),
                                  child: Text(
                                    'Learning Exchange',
                                    style: AwakText.body16Style.copyWith(
                                      fontWeight: FontWeight.w800,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            Row(
                              children: [
                                Padding(
                                  padding: EdgeInsets.symmetric(
                                    horizontal: 16.w,
                                    vertical: 4.h,
                                  ),
                                  child: Text(
                                    'Lifelong Learning Eliminates Cognitive Ambiguity',
                                    style: AwakText.body14Style.copyWith(
                                      fontWeight: FontWeight.w400,
                                      fontSize: 10.sp,
                                      color: Colors.black.withValues(
                                        alpha: 0.7,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            SizedBox(height: 10.h),
                            Builder(
                              builder: (context) {
                                // 使用缓存的房间数据
                                List<Room> allRooms = _cachedRooms;

                                // 获取所有房间列表
                                List<Room> rooms = _getAllRooms(allRooms);

                                // 为每个房间加载评论数据
                                for (Room room in rooms) {
                                  if (room.id != null &&
                                      !_roomCommentsCache.containsKey(
                                        room.id,
                                      )) {
                                    _loadRoomComments(room);
                                  }
                                }

                                // 按评论数量排序，评论最多的在前面
                                rooms.sort((a, b) {
                                  int aComments = _getRoomCommentCount(a);
                                  int bComments = _getRoomCommentCount(b);
                                  return bComments.compareTo(aComments);
                                });

                                if (rooms.isEmpty) {
                                  return Container(
                                    margin: EdgeInsets.symmetric(
                                      horizontal: 16.w,
                                      vertical: 20.h,
                                    ),
                                    padding: EdgeInsets.all(20.w),
                                    decoration: BoxDecoration(
                                      color: Colors.grey.withValues(alpha: 0.1),
                                      borderRadius: BorderRadius.circular(12.r),
                                      border: Border.all(
                                        color: Colors.grey.withValues(
                                          alpha: 0.3,
                                        ),
                                      ),
                                    ),
                                    child: Text(
                                      'No rooms available yet. Create your first room!',
                                      textAlign: TextAlign.center,
                                      style: AwakText.body14Style.copyWith(
                                        color: Colors.grey,
                                      ),
                                    ),
                                  );
                                }

                                List<Widget> rows = [];
                                for (int i = 0; i < rooms.length; i += 2) {
                                  List<Widget> rowChildren = [
                                    SizedBox(width: 8.w),
                                  ];

                                  rowChildren.add(
                                    _buildLearningRoomCard(
                                      rooms[i],
                                      i < defaultButton.length
                                          ? defaultButton[i %
                                                defaultButton.length]
                                          : 'Join',
                                      i < defaultPeople.length
                                          ? defaultPeople[i %
                                                defaultPeople.length]
                                          : '${rooms[i].id ?? 0} People',
                                    ),
                                  );

                                  rowChildren.add(SizedBox(width: 8.w));

                                  if (i + 1 < rooms.length) {
                                    rowChildren.add(
                                      _buildLearningRoomCard(
                                        rooms[i + 1],
                                        (i + 1) < defaultButton.length
                                            ? defaultButton[(i + 1) %
                                                  defaultButton.length]
                                            : 'Join',
                                        (i + 1) < defaultPeople.length
                                            ? defaultPeople[(i + 1) %
                                                  defaultPeople.length]
                                            : '${rooms[i + 1].id ?? 0} People',
                                      ),
                                    );
                                  } else {
                                    rowChildren.add(
                                      Expanded(child: SizedBox()),
                                    );
                                  }

                                  rowChildren.add(SizedBox(width: 8.w));

                                  rows.add(
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: rowChildren,
                                    ),
                                  );

                                  if (i + 2 < rooms.length) {
                                    rows.add(SizedBox(height: 10.h));
                                  }
                                }

                                return Column(children: rows);
                              },
                            ),
                            SizedBox(height: 130.h),
                          ],
                        )
                      : _buildCommunityContent(), // 显示 Community 内容
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
